﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Data.Xml.Dom;
using Beyondsoft.Tuanju.DataManager.DealProviders;
using Windows.ApplicationModel;

namespace Beyondsoft.Tuanju.DataManager
{
    public static class Settings
    {
        private static IDictionary<string, DealProvider> providers = new Dictionary<string, DealProvider>();

        public static IDictionary<string, DealProvider> Providers
        {
            get
            {
                return providers;
            }
        }

        public async static Task Initialize()
        {
            if (providers.Count ==0)
            {
                providers = await GetProviders();
            }
        }

        private static async Task<IDictionary<string, DealProvider>> GetProviders()
        {
            StorageFolder storageFolder = await Package.Current.InstalledLocation.GetFolderAsync("Beyondsoft.Tuanju.DataManager");
            StorageFolder dataFolder = await storageFolder.GetFolderAsync("Configuration");

            var poviderFile = await dataFolder.GetFileAsync("Providers.xml");

            XmlDocument xdoc = await XmlDocument.LoadFromFileAsync(poviderFile);

            var providerNodes = xdoc.SelectNodes("providers/provider");

            Dictionary<string, DealProvider> providers = new Dictionary<string, DealProvider>();

            foreach (var node in providerNodes)
            {
                string name = node.Attributes[0].InnerText;
                var p = DealProvider.CreateProvider(name);

                if (p != null && await p.IsAvailable()) 
                {
                    providers.Add(name, p);
                }
            }

            return providers;
        }
    }
}
